package com.passion.interceptor;

import com.alibaba.fastjson.JSONObject;
import org.apache.flume.Context;
import org.apache.flume.Event;
import org.apache.flume.interceptor.Interceptor;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @program data-collection
 * @Description
 * @Author limeihua
 * @Date 2024/09/11 11:25
 * @Version 1.0
 */
public class TimestampTableInterceptor implements Interceptor {
    @Override
    public void initialize() {

    }

    @Override
    public Event intercept(Event event) {
        byte[] body = event.getBody();
        Map<String, String> headers = event.getHeaders();
        JSONObject jsonObject = JSONObject.parseObject(new String(body));
        String ts = jsonObject.getString("ts") + "000";
        String tableName = jsonObject.getString("table");
        headers.put("timestamp", ts);
        headers.put("tableName", tableName);
        event.setHeaders(headers);
        return event;
    }

    @Override
    public List<Event> intercept(List<Event> list) {
        ArrayList<Event> events = new ArrayList<>();
        for (Event event : list) {
            Event intercept = intercept(event);
            events.add(intercept);
        }
        return events;
    }

    @Override
    public void close() {

    }

    public static class Builder implements Interceptor.Builder {

        @Override
        public Interceptor build() {
            return new TimestampTableInterceptor();
        }

        // 配置参数
        @Override
        public void configure(Context context) {

        }
    }
}
